//app.js
var util = require('utils/util.js')
var utilMd5 = require('utils/md5.js');
App({

  screen_w: 320,
  screen_h: 480,
  isIphone_x: false,

  globalData: {
    userInfo: '',
    cuid: '',
    token: '',
    openid: '',
    imgDomain: util.api_host + '/wechat',
    canSelHotelNameArr: '',
    hotelSelectIndex: -1,
    allRoomData: '',

    allImages: [],
    allVideos: [],

    shenhe_ctr: -1,

    lastGetRegisterUserTime: 0,
    newRegisterUid: '',

    tmplMsgIds: 'ug5pyTLlU7VeUGlPpp4NzhBuGu9mQgFrxI07kGH35t0'
  },

  onLaunch: function () {
    //调用API从本地缓存中获取数据
    var that = this;
    //底部导航数据
    tt.removeStorageSync('navData0');
    tt.removeStorageSync('navData1');
    //颜色配置信息
    tt.removeStorageSync('color_set');

    // tt.clearStorageSync();
    
  },

  initScreenInfo: function(cb = null) {
    var that = this
    tt.getSystemInfo({
      success: function (res) {
        console.log("system info:", res);
        that.isIphone_x = (res.model.indexOf('iPhone X') >= 0)
        that.screen_w = res.windowWidth
        that.screen_h = res.windowHeight
        typeof cb == "function" && cb(true)
      }
    })
  },

  getLocation: function (cb = null) {
    tt.getLocation({
      type: 'gcj02',
      isHighAccuracy: false,
      success(res) {
        console.log('getLocation==', res);
        typeof cb == "function" && cb(res)
      },
      fail(res) {
        console.log('fail==', res);
        typeof cb == "function" && cb(res)
      }
    });
  },

  setSubscribeMessageCache: function () {
    let curDate = new Date()
    let curTime = curDate.getTime() / 1000
    tt.setStorage({
      key: "smcachetime",
      data: curTime
    })
  },
  noSubscribeMessageCache: function () {
    let noChche = true
    let cacheTime = tt.getStorageSync('smcachetime')
    if (cacheTime && cacheTime > 0) {
      let curDate = new Date()
      let curTime = curDate.getTime() / 1000
      if (curTime - cacheTime < 12* 3600) {
        noChche = false
      }
    }
    return noChche
  },
  removeSubscribeMessageCache() {
    tt.removeStorageSync('smcachetime');
  },

  getWxCheck:function (cb, reget = false) {
    var that = this
    if (that.globalData.shenhe_ctr != -1 && !reget) {
      typeof cb == "function" && cb(that.globalData.shenhe_ctr)
    } else {
      util.api({
        data: {
          "publickey": util.publiccode,
          "ac": "wxcheck"
        },
        success: function (responseData) {
          console.log("微信审核开关:", responseData)
          if (responseData.errMsg == "request:ok") {
            that.globalData.shenhe_ctr = responseData.data.isShow
            typeof cb == "function" && cb(that.globalData.shenhe_ctr)
          } else {
            that.globalData.shenhe_ctr = -1
            typeof cb == "function" && cb(false)
          }
        },
        fail: function(err) {
          console.log("微信审核开关 fail:", err)
          that.globalData.shenhe_ctr = -1
          typeof cb == "function" && cb(false)
        }
      });
    }
    
  },

  /**
   * cb 回调函数
   * regetLoginUserData 是否重新获取登录用户信息，在编辑用户资料后，需要重新获取
   */
  LoginUserInfo: function(cb, regetLoginUserData = false){
    if (this.globalData.cuid && this.globalData.token && this.globalData.openid) {
      //已静默授权登录
      if (this.globalData.userInfo && !regetLoginUserData) {
        //已获取用户信息 直接返回缓存信息
        typeof cb == "function" && cb(this.globalData.userInfo)
      } else {
        var that = this
        //重新去获取登录用户信息
        this.getUserInfo(this.globalData.cuid, function(res) {
          if(res != -1) {
            that.globalData.userInfo = res
            typeof cb == "function" && cb(that.globalData.userInfo)
          } else {
            typeof cb == "function" && cb('-1')
          }
        })
      }
    } else {
      //未静默授权登录；每次完全重新启动时重新静默授权一次
      this.wxLoginRequest(cb)
    }   
  },

  /**微信静默授权登录 */
  wxLoginRequest: function(cb){
    var that = this
    tt.login({
      success: (res) => {
        console.log("抖音登录 response:", res)
        util.api_go({
          method:"POST",
          data: {ac: "ttLogin", phone: "", code: res.code},
          success: function(responseData) {
            console.log("ttLogin success",responseData);
            if (responseData.data.msg) {
              typeof cb == "function" && cb('-1')
            } else {
              that.globalData.cuid = responseData.data.uid
              that.globalData.token = responseData.data.token
              that.globalData.openid = responseData.data.openid
              that.getUserInfo(responseData.data.uid, cb)
            }
          },
          fail:function(res){
            console.log("获取openid fail",res);
            typeof cb == "function" && cb('-1')
          }
        })
      },
      fail: (res) => {
        console.log("wxLoginRequest fail:", res)
      }
    })
  },


  //获取某个用户id的信息
  getUserInfo: function(uid, cb) {
    util.api({
        data: {
          "publickey": util.publiccode,
          "ac": "userinfo",
          "uid": uid
        },
        success: function (responseData) {
          console.log("用户信息：", responseData);
          if(responseData.data.uid) {
            var res = responseData.data
            typeof cb == "function" && cb(res)
          } else {
            typeof cb == "function" && cb(-1)
          }
          
        }
      });
  },

  //获取关于  售后保障  联系方式 dataName: about-关于  shouhou-售后  contact-联系方式
  getAllAbout: function (dataName, cb) {
      util.api({
        data: {
          "publickey": util.publiccode,
          "ac": "about",
          "uid": util.orgid
        },
        success: function (responseData) {
          console.log("所有关于数据：", responseData);
          var allData = responseData.data;
          var res = allData[dataName];
          typeof cb == "function" && cb(res)
        }
      });
    
  },

  //设置语言标识（简体/繁体）标识
  set_tc: function(tc){
    tt.setStorageSync('tc', tc);
    console.log("setStorageSync简体/繁体 tc =" + tc + "!");
  },
  //获取语言（简体/繁体）标识 1:繁体 else 简体
  get_tc: function(){
    var tc = tt.getStorageSync('tc');
    if (util.orgid == 20510&&tc){
      return tc
    }
    console.log("简体/繁体 tc =" + tc + "!");
    if (!tc && -1 != tc) {
      tc = 0;
    } else if (-1 == tc){
      tc = 1;
    }
    console.log("简体/繁体 tc = " + tc); 
    if (util.orgid == 19619 || util.orgid == 20510 || util.orgid == 12545 || util.orgid == 13078 || util.orgid == 14148 || util.orgid == 15938|| util.orgid == 21398){
      tc=1;
      return tc ;
    }
    else{
      return tc;
    }
  },

  //获取底部导航数据
  getBottomNavData: function (path, cb) {
    var that=this;
    var dataKey = 'navData' + this.get_tc();
    //先判断缓存中有无数据
    var navData = tt.getStorageSync(dataKey);
    if (navData) {
      console.log("底部导航数据:", navData);
      navData.forEach(function (m, i) {
        if (m.data.indexOf(path) > 0) {
          m.path = '';
          m.class = 'curr';
          m.img = m.bimage;
          m.color = m.btcolor;
        } else {
          m.img = m.fimage;
          m.color = m.ftcolor;
          m.path = m.data;
        }
        m.text = m.title;
      });
      typeof cb == "function" && cb(navData);
    } else {
      var params = {
        "publickey": util.publiccode,
        "ac": "getnav",
        "uid": util.orgid,
        "tc": this.get_tc()
      };
      util.api({
        data: params,
        success: function (responseData) {
          console.log("底部导航数据:", responseData);
          var result = responseData.data;
          if (result && result.length > 0) {
            tt.setStorageSync(dataKey, result);
            result.forEach(function (m, i) {
              if (m.data.indexOf(path) > 0) {
                m.path = '';
                m.class = 'curr';
                m.img = m.bimage;
                m.color = m.btcolor;
              } else {
                m.img = m.fimage;
                m.color = m.ftcolor;
                m.path = m.data;
              }
              m.text = m.title;
            });
            typeof cb == "function" && cb(result);
          }
        }
      });
    }
       
  },

  getColorSetData: function(cb){
    // titlebg - 标题栏背景色 titlefont- 标题栏文字色 btnbg- 按钮背景色 btnfont- 按钮字体色 pricecolor- 价格色
    var colorData = tt.getStorageSync("color_set");
    if(colorData){
      typeof cb == "function" && cb(colorData);
    } else {
      var that = this;
      var params = {
        ac: "colorset",
        publickey: util.publiccode,
        uid: util.orgid,
      };
      // console.log("获取视频源地址 参数： ", params);
      util.api({
        data: params,
        success: function (responseData) {
          console.log("获取颜色配置数据： ", responseData);
          var result = responseData.data;
          tt.setStorageSync("color_set", result);
          typeof cb == "function" && cb(result);
        }
      });
    }
  },

  //获取是否显示广告的标记
  getShowGuanggaoSign: function(key, maxCount){
    var date = new Date();
    var day = date.getDate();
    var time = parseInt(date.getTime() / 1000);
    var lastShowInfo = tt.getStorageSync(key, '');
    console.log("原广告显示记录：dis seconds = " + (time - lastShowInfo.time), lastShowInfo);
    if (!lastShowInfo || lastShowInfo.day != day 
      || (lastShowInfo.count < maxCount //今天还有显示次数
      && time - lastShowInfo.time >= 7200)){//并间隔两小时才显示
      return true;
    } else {
      return false;
    }
  },

  //设置最后一次显示广告的标记
  setShowGuanggaoSign: function (key) {
    var date = new Date();
    var day = date.getDate();
    var time = parseInt(date.getTime() / 1000);
    var lastShowInfo = tt.getStorageSync(key, '');
    if(!lastShowInfo){
      lastShowInfo = {};
    }
    var count = 1;
    if(lastShowInfo.day == day){
      count = lastShowInfo.count + 1;
    }
    lastShowInfo.day = day;
    lastShowInfo.time = time;
    lastShowInfo.count = count;
    console.log("设置广告显示记录：", lastShowInfo);
    tt.setStorage({
      key: key,
      data: lastShowInfo
    })
  },


  //计算两个经纬度点的距离
  getDistance: function (lat1, lng1, lat2, lng2) {
    lat1 = lat1 || 0;
    lng1 = lng1 || 0;
    lat2 = lat2 || 0;
    lng2 = lng2 || 0;

    var rad1 = lat1 * Math.PI / 180.0;
    var rad2 = lat2 * Math.PI / 180.0;
    var a = rad1 - rad2;
    var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;

    var r = 6378137;
    return r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)))
  },

  getDistanceStr: function(distanceInt) {
    var distanceStr = ""
    if(distanceInt < 1000) {
      distanceStr = distanceInt.toFixed(0) + "m"
    } else {
      distanceStr = (distanceInt / 1000).toFixed(2) + 'km'
    }
    return distanceStr
  },

  //获取腾讯视频 源链接
  getVideoSrcLink: function (index, videoLink, cb) {
    var that = this;
    var params = {
      ac: "xcxvideo",
      publickey: util.publiccode,
      url: videoLink
    };
    // console.log("获取视频源地址 参数： ", params);
    util.api({
      data: params,
      success: function (responseData) {
        console.log("获取视频源地址 返回： ", responseData);
        if (responseData.data.res) {
          typeof cb == "function" && cb(responseData.data.url, index)
        } else {
          typeof cb == "function" && cb(-1, -1)
        }
      }
    });
  },

  //保存 模版消息 的推送 formid
  saveFormId: function (formid) {
    
  },
  
  //消息提示
  dialog: function(title, icon, cb) {
    tt.showToast({
      title: title,
      icon: icon,
      duration: 2000
    });
    setTimeout(function(){
      tt.hideToast()
    }, icon =='success' ? 2000:1000)
    typeof cb == "function" && cb()
  },

  //消息提示
  dialogToast: function (title, icon, cb) {
    tt.showToast({
      title: title,
      icon: icon,
      duration: 1500
    });
    setTimeout(function () {
      typeof cb == "function" && cb()
    }, 1500)

  },

  parseHTMLText: function (htmlSrc) {
    if (!htmlSrc && htmlSrc.length <= 0) return '';

    var str = htmlSrc.length > 300 ? htmlSrc.substring(0, 300) : htmlSrc;
    str = str.replace(/[\r\n]/g, '');
    // console.log("替换<br>后：" + str);

    str = str.replace(/^\s+|\s+$/g, '');     //去掉首尾多余的换行
    // console.log("替换<br>后：" + str);

    str = str.replace(/<br>/g, '\n'); //替换 <br> 为 \n
    // console.log("替换<br>后：" + str);

    str = str.replace(/<br\/>/g, '\n'); //替换 <br> 为 \n
    str = str.replace(/<br \/>/g, '\n'); //替换 <br> 为 \n
    // console.log("替换<br>后：" + str);

    str = str.replace(/<\/?[^>]*>/g, ''); //去除HTML tag
    // console.log("去除HTML tag：" + str);

    str = str.replace(/[ | ]*\n/g, '\n'); //去除行尾空白
    // console.log("去除行尾空白：" + str);

    // str = str.replace(/\n[\s| | ]*\r/g,'\n'); //去除多余空行
    // console.log("去除多余空行：" + str);

    str = str.replace(/&nbsp;/ig, '');//去掉&nbsp;
    // console.log("去掉&nbsp：" + str);

    str = str.replace(/&mdash;/ig, '');//去掉&mdash;
    // console.log("去掉&mdash：" + str);

    // str = str.replace(/\s/g, ''); //将空格去掉
    // console.log("将空格去掉：" + str);
    return str;
  },


  showWXMadal:function(contentStr){
    tt.showModal({
      title: '温馨提示',
      content: contentStr,
      showCancel: false
    })
  },

  //获取该用户所有已上传的图片信息
  getAllUpladedImages: function(userId, reget = false, cb) {
    var that = this;
    if (!reget) {
      if(this.globalData.allImages.length > 0) {
        typeof cb == "function" && cb(that.globalData.allImages)
        return
      }
    }
    util.api_go({
      data: {
        "publickey": util.publiccode,
        "ac": "getimages",
        "postuid": userId
      },
      success: function(responseData) {
        console.log("获取该用户所有已上传的相册信息：", responseData);
        if (!responseData.data.msg) {
          if(userId == that.globalData.cuid) {
            that.globalData.allImages = responseData.data
          }
          typeof cb == "function" && cb(responseData.data)
        } else{
          typeof cb == "function" && cb(0)
        }
      },
      fail: function(e) {
        console.log("获取该用户所有已上传的相册信息失败");
        typeof cb == "function" && cb(-1)
      }
    });
  },

  //获取该用户所有已上传的视频信息
  getAllUpladedvideos: function(userId, reget = false, cb) {
    var that = this;
    if (!reget) {
      if(this.globalData.allVideos.length > 0) {
        typeof cb == "function" && cb(that.globalData.allVideos)
        return
      }
    }
    util.api_go({
      data: {
        "publickey": util.publiccode,
        "ac": "getvideos",
        "postuid": userId
      },
      success: function(responseData) {
        console.log("获取该用户所有已上传的视频信息：", responseData);
        if (!responseData.data.msg) {
          if(userId == that.globalData.cuid) {
            that.globalData.allVideos = responseData.data
          }
          typeof cb == "function" && cb(responseData.data)
        } else{
          typeof cb == "function" && cb(0)
        }
      },
      fail: function(e) {
        console.log("获取该用户所有已上传的视频信息失败");
        typeof cb == "function" && cb(-1)
      }
    });
  },

  //增加用户信息条数
  addMessageCount: function(msgCount, cb) {
    var that = this;
    let privateKey = utilMd5.hexMD5(this.globalData.cuid + "addcoinnum" + this.globalData.token);
    let commitData = {
      "privatekey": privateKey,
      "ac": "addcoinnum",
      "uid": this.globalData.cuid,
      "nums": msgCount
    };
    console.log("增加用户信息条数：", commitData)
    util.api_go({
      data: commitData,
      method: "POST",
      success: function(responseData) {
        console.log("用户信息条数", responseData);
        if (responseData.data.res) {
          //保存成功
          typeof cb == "function" && cb(responseData.data)
        } else {
          tt.showToast({
            title: responseData.data.msg,
          })
          typeof cb == "function" && cb(-1)
        }
      }
    });
  },

  userInfoIsComplete:function (userTag, showModal = false) {
    let complete = (userTag.indexOf("1") >= 0 && userTag.indexOf("2") >= 0 
    && userTag.indexOf("3") >= 0 && userTag.indexOf("4") >= 0)
    if (showModal && !complete) {
      tt.showModal({
        title: '温馨提示',
        content: '您还未完善个人资料，请马上完善资料，立即获取免费信息条数与帅哥美女畅聊吧～',
        confirmText: '去完善',
        complete: (res) => {
          if (res.confirm) {
            tt.navigateTo({
              url: '/pages/mineInfoEdit/mineInfoEdit'
            })
          }
        }
      })
    }
    return complete
  },

  debug: true
})